package com.asiainfo.complier.editor;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;

import javax.swing.JPanel;

public class LinePanel extends JPanel {

	/**
	 * LinePanel
	 */
	private static final long serialVersionUID = -2484439673372907294L;

	private String maxLine;
	private CoderEditor editor;
	private int startLine;

	public int getEndLine() {
		return endLine;
	}

	public void setEndLine(int endLine) {
		this.endLine = endLine;
	}

	public int getStartLine() {
		return startLine;
	}

	public void setStartLine(int startLine) {
		this.startLine = startLine;
	}

	private int endLine;

	public LinePanel(final CoderEditor editor) {
		setBackground(Color.white);
		this.editor = editor;
		startLine = 0;
		endLine = 0;
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				Point p = e.getPoint();
				int x = p.y;
				int line = startLine + x / editor.getEditor().getRowHeight()
						- 1;
				if (line >= 0)
					editor.getEditor().go2Line(line);

			}
		});
	}

	/**
	 * Update LineInfo
	 * 
	 * @param startLine
	 * @param endLine
	 */
	public void UpdateLineInfo(int startLine, int endLine) {
		this.startLine = startLine;
		this.endLine = endLine;
		maxLine = endLine + " ";
		Graphics g = this.getGraphics();
		FontMetrics fts = g.getFontMetrics();
		Rectangle2D rc = fts.getStringBounds(maxLine, g);
		int w = rc.getBounds().width;
		this.setPreferredSize(new Dimension(w + 1, -1));
		this.updateUI();
		repaint();
	}

	public void paint(Graphics g) {

		super.paint(g);

		int rowHeight = editor.getEditor().getRowHeight();
		FontMetrics fts = g.getFontMetrics();
		Rectangle2D rc = fts.getStringBounds(maxLine, g);
		int h = rc.getBounds().height;
		g.setColor(new Color(0xD4, 0xD0, 0xC8));
		if(startLine<=0) startLine=1;
		for (int i = startLine; i <= endLine; i++) {
			int x = 0;
			int y = (i - startLine + 1) * rowHeight - h / 2 + fts.getAscent()
					/ 2;

			g.drawString(" " + i + "", x, y);

		}
	}

}
